﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace Autofac
{
    public class AutofacModuleRegister : Autofac.Module
    {
        private readonly Assembly _servicesToScan;
        private readonly Assembly _iservicesToScan;
        private readonly IConfigurationSection _redisSection;
        private readonly string _appModuleName;

        /// <summary>
        /// 统一注册WebApi通用模块
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configuration"></param>
        /// <param name="serverInfo"></param>
        /// <param name="completedExecute"></param>
        /// <returns></returns>
        public AutofacModuleRegister(ContainerBuilder builder, IServiceCollection services, Action<ContainerBuilder> completedExecute = null)
        {
            var configuration = services.GetConfiguration();
            var serviceInfo = services.GetServiceInfo();

            _iservicesToScan = Assembly.Load(serviceInfo.AssemblyName.Replace("WebApi", "IServices"));
            _servicesToScan = Assembly.Load(serviceInfo.AssemblyName.Replace("WebApi", "Services"));

            _appModuleName = serviceInfo.ShortName;
            _redisSection = configuration.GetRedisSection();
        }

        protected override void Load(ContainerBuilder builder)
        {
            //注册依赖模块
            this.LoadDepends(builder);
        }

        private void LoadDepends(ContainerBuilder builder)
        {
            //builder.RegisterModule<AutofacEFModule>();
            //builder.RegisterModule(new AutofacCachingModule(_redisSection));
            //builder.RegisterModule(new AutofacEventBusModule(_servicesToScan));;


            // 获取 IService.dll 程序集服务，并注册
            builder.RegisterAssemblyTypes(_iservicesToScan)
                      .AsImplementedInterfaces()// 是以接口方式进行注入
                       .PropertiesAutowired()//属性注入
                       .InstancePerDependency();//默认模式，每次调用，都会重新实例化对象；每次请求都创建一个新的对象；


        }
    }
}
